import { verifyMenuAuthApi, verifyUserApi } from '@/common/api/sessionAuth';
import router from '@/router';
import { UserModule } from '@/store/modules/user';
import Axios from '@/utils/request';
import { getConfigItem } from './tools';

const WEB_DOCKING = getConfigItem('WEB_DOCKING');
const prefix: string = WEB_DOCKING.toLowerCase() + '-';
const docking: string = WEB_DOCKING.toUpperCase();
const routerMode: string = process.env.ROUTER_MODE;
const baseUrl = getConfigItem('BASE_URL_API');

export const AuthenticationMd5Key = 'jfm-yhfin-value';

export const SET_CACHE = (cacheName: string, obj: any): void => {
    if (!cacheName || !obj) {
        return;
    }
    sessionStorage.setItem(prefix + cacheName, JSON.stringify(obj));
};

export const GET_CACHE = (cacheName: string): any => {
    return JSON.parse(sessionStorage.getItem(prefix + cacheName)) || null;
};

export const DELETE_CACHE = (cacheName: string): void => {
    sessionStorage.removeItem(prefix + cacheName);
};

/**
 * 获取当前User详情
 * user对象
 * {
 * "fundResource":[],
 * "resources":[],
 * "sessionId":"61879483-bb33-4868-a936-d1144f445a70",
 * "superuser":false,
 * "userCode":"4",
 * "userName":"****"
 * }
 */
export const getUser = (): any => {
    return GET_CACHE('user') || {};
};

export const setUser = (obj: any): void => {
    SET_CACHE('user', obj);
};

export const removeUser = (): void => {
    DELETE_CACHE('user');
};

export const getActiveMenuCode = (): any => {
    return GET_CACHE('activeMenuCode') || {};
};

export const setActiveMenuCode = (obj: any): void => {
    SET_CACHE('activeMenuCode', obj);
};

export const getSystem = (): any => {
    return GET_CACHE('system') || [];
};

export const setSystem = (sys: any): void => {
    SET_CACHE('system', sys);
};

export const getPathInfo = () => {
    let href = JSON.parse(JSON.stringify(document.location.href));
    let origin = JSON.parse(JSON.stringify(document.location.origin));

    // 兼容 nginx 转发造成的 href 与 origin 页面环境源不同
    href = href.replace('/YH/', '/').replace('/dist/', '/');
    origin = origin.replace('/YH/', '/').replace('/dist/', '/');

    const addr = href.substr(origin.length);
    const sessionId = addr.substr(addr.indexOf('?') + 1).split('=')[1];

    let url: string;
    // 去除后面参数
    if (addr.indexOf('?') > -1) {
        url = addr.substr(0, addr.indexOf('?'));
    } else {
        url = addr.substr(0);
    }
    // 去除部署目录
    const deploymentDirectory = routerMode === 'history' ? '' : '/#';
    url = url.substr(deploymentDirectory.length);

    return {
        sessionId,
        url,
    };
};

/**
 * 用户验证
 */
export const verifyUser = (): Promise<any> => {
    return new Promise<any>((resolve, reject) => {
        let result;
        if (['RISK', 'ZSJJ', 'PYAXA', 'MAXWEALTH', 'SPRINGSCAPITAL', 'FSCINDA', 'CMSCHINA', 'SINOSIG', 'LIONFUND', 'CIBFUND', 'HUATAI'].includes(docking)) {
            if (docking == 'MAXWEALTH') {
                // 设置永赢可单点登录
                let token: string = '';
                let url: string = '';
                const session = getPathInfo().sessionId || getUser()?.sessionId;
                const type = getUser()?.themeType === '1' ? 'light' : 'blue'; // 当前主题

                let href = JSON.parse(JSON.stringify(document.location.href));
                let origin = JSON.parse(JSON.stringify(document.location.origin));

                // 兼容 nginx 转发造成的 href 与 origin 页面环境源不同
                href = href.replace('/YH/', '/');
                origin = origin.replace('/YH/', '/');

                const addr = href.substr(origin.length);

                if (addr.indexOf('?user') !== -1) {
                    token = addr.substr(addr.indexOf('?user') + 1).split('=')[1];
                }
                // const token = getPathInfo().sessionId;
                if (token) {
                    url = `${baseUrl}/sessionAuth/verifyUser?user=${token}`;
                } else {
                    url = `${baseUrl}/sessionAuth/verifyUser?sessionId=${session}`;
                }
                // 改变子页面的主题颜色(由于主题色失效,先暂时写死)
                try {
                    const frames = window.frames;
                    frames.document.body.setAttribute('data-theme', 'blue');
                } catch (e) {
                    console.log(e);
                }
                // try {
                //     const frames = window.frames;
                //     frames.document.body.setAttribute('data-theme', type);
                // } catch (e) {
                //     console.log(e);
                // }
                Axios.get(url)
                    .then(result => {
                        setUser(result);
                        resolve(result);
                    })
                    .catch(err => {
                        reject(err);
                    });
            } else {
                const session = getPathInfo().sessionId || getUser()?.sessionId;
                verifyUserApi(session)
                    .then(result => {
                        setUser(result);
                        resolve(result);
                    })
                    .catch(err => {
                        reject(err);
                    });
            }
        } else {
            reject(new Error('docking未设置'));
        }
    });
};

/**
 * 菜单验证
 */
export const verifyMenuAuth = (): Promise<boolean> => {
    return new Promise((resolve, reject) => {
        const url = getPathInfo().url;
        verifyMenuAuthApi(url)
            .then(result => {
                resolve(result);
            })
            .catch(error => {
                reject(error);
            });
    });
};

/**
 * 根据路由获取相应的菜单资源编码
 * @param path 路径
 * @return 菜单资源编码
 */
export const getResourceCode = (path: string) => {
    console.log(`[----------前端HTTP埋点: ${path} ----------]`);
    if (path.search(/resourceCode=/) !== -1) {
        return path.slice(path.search(/resourceCode=/) + 'resourceCode='.length) || '';
    }

    const resources = getUser()?.resources || [];
    const menu = resources.find(item => {
        return path.indexOf(item.menuUrl) !== -1 && item.resourceParentCode !== '0';
    });
    return menu?.resourceCode || '';
};
